//
//  WLMComposeViewController.swift
//  WeiBo
//
//  Created by Eric on 2017-01-13.
//  Copyright © 2017 Eric. All rights reserved.
//

import UIKit
import SVProgressHUD

enum SendWeiBoType: Int {
    case SendPhoto = 0
    case AtPerson
    case Topic
    case Emoticon
    case More
}


class WLMComposeViewController: UIViewController {

    
    //MARK: - 懒加载
    lazy var textView: UITextView = {
        let txtView = UITextView()
        txtView.backgroundColor = UIColor.white
        txtView.textColor = UIColor.darkGray
        txtView.font = UIFont.systemFont(ofSize: 18)
        txtView.alwaysBounceVertical = true
        txtView.keyboardDismissMode = .onDrag
        txtView.delegate = self
        return txtView
    }()
    
    //站位文本
    lazy var placeHolderLabel: UILabel = UILabel(text: "Whatever you want to type, please type here...", fonSize: 18, textColor: UIColor.lightGray)
    
    //懒加载自定义键盘视图
    lazy var keyboardView: HMEmoticonKeyboardView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: 220))
    
    //自定义发送
    lazy var sendItem: UIBarButtonItem = {
        let btn = UIButton()
        btn.setTitle("send", for: .normal)
        btn.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
        btn.setTitleColor(#colorLiteral(red: 0.6642242074, green: 0.6642400622, blue: 0.6642315388, alpha: 1), for: .disabled)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white"), for: .disabled)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.addTarget(self, action: #selector(send), for: .touchUpInside)
        btn.sizeToFit()
        btn.bounds.size.width = 50
        let barItem = UIBarButtonItem(customView: btn)
        barItem.isEnabled = false
        return barItem
    }()
    
    //底部工具栏
    lazy var toolBar: UIStackView = {
        let stack = UIStackView()
        //设置轴
        stack.axis = .horizontal
        //设置填充方式
        stack.distribution = .fillEqually
        
        //添加按钮 并且监听按钮的点击事件
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        for (offset, imageName) in imageNames.enumerated() {
            //实例化按钮对象
            let btn = UIButton()
            btn.tag = offset
            btn.setImage(UIImage(named: imageName), for: .normal)
            btn.setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted)
            btn.backgroundColor = UIColor(white: 0.9, alpha: 1)
            
            //添加事件
            btn.addTarget(self, action: #selector(clickedWeiBoType(button:)), for: .touchUpInside)
            
            //添加按钮
            stack.addArrangedSubview(btn)
        }
        return stack
    }()

    @objc private func clickedWeiBoType(button: UIButton) {
        let type = SendWeiBoType(rawValue: button.tag)!
        switch type {
        case .SendPhoto:
            print("发送图片")
            pictureSelector.userWillAddPic()
        case .AtPerson:
            print("@人")
        case .Topic:
            print("话题")
        case .Emoticon:
            print("表情")
            textView.inputView = textView.inputView == nil ? keyboardView : nil
            textView.reloadInputViews()
        case .More:
            print("更多")
        }
    }
    //关闭
    func close() {
        textView.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    lazy var pictureSelector: WLMPictureSelectorController = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: selectorItemWidth, height: selectorItemWidth)
        flowLayout.minimumLineSpacing = selectorCellMargin
        flowLayout.minimumInteritemSpacing = selectorCellMargin
        flowLayout.sectionInset = UIEdgeInsetsMake(selectorCellMargin, selectorCellMargin, 0, selectorCellMargin)
        let viewController = WLMPictureSelectorController(collectionViewLayout: flowLayout)
        
        return viewController
    }()
    
    //发送
    func send() {
        textView.endEditing(true)
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        guard let accesstoken = WLMUserAccountViewModel.shared.access_token else {
            return
        }
        let parameters: [String : String] = ["access_token" : accesstoken, "status" : textView.imageEmoticon2Chs()]
        
        if pictureSelector.images.count == 0 {
            SVProgressHUD.show()
            WLMNetworkTools.sharedManager.request(method: .POST, URLString: urlString, parameters: parameters, finished: { (response, error) -> () in
                if error != nil {
                    SVProgressHUD.dismiss()
                    SVProgressHUD.showError(withStatus: "发布微博失败")
                    return
                }
                //发布微博成功
                SVProgressHUD.dismiss()
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
                self.dismiss(animated: true, completion: nil)
                
            })
        }
        else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            SVProgressHUD.show()
            WLMNetworkTools.sharedManager.post(urlString, parameters: parameters, constructingBodyWith: { (formData) in
                let image = self.pictureSelector.images.last!
                let imageData = UIImagePNGRepresentation(image)!
                formData.appendPart(withFileData: imageData, name: "pic", fileName: "xxxxxx", mimeType: "application/octet-stream")
            }, progress: nil, success: { (_, response) in
                SVProgressHUD.dismiss()
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
                self.dismiss(animated: true, completion: nil)
            }, failure: { (_, error) in
                SVProgressHUD.dismiss()
                SVProgressHUD.showError(withStatus: "发布微博失败")
                return
            })
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        setNaviBar()
        setTextView()
        setToolBar()
        registerNotification()
        setSelectorController()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //成为第一响应者
        textView.becomeFirstResponder()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        pictureSelector.view.isHidden = pictureSelector.images.count == 0
    }
    
    private func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //注册键盘中按钮点击事件
        NotificationCenter.default.addObserver(self, selector: #selector(insertEmoticon(notifi:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
    }
    
    @objc private func insertEmoticon(notifi: Notification) {
        
        textView.inputEmoticon(emoticon: notifi.object as? HMEmoticon)
//        guard let emoji = notifi.object as? HMEmoticon else {
//            textView.deleteBackward()
//            return
//        }
//        if emoji.type == 1 {
//            textView.replace(textView.selectedTextRange!, withText: emoji.emojiStr ?? "")
//            return
//        }
//        let image = UIImage(named: emoji.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
//        let attachement = NSTextAttachment()
//        let lineHeight = textView.font?.lineHeight ?? 0
//        attachement.bounds = CGRect(x: 0, y: 0, width: lineHeight, height: lineHeight)
//        attachement.image = image
//        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachement))
//        imageText.addAttributes([NSFontAttributeName : textView.font!], range: NSRange(location: 0, length: 0))
//        let mutaStr = NSMutableAttributedString(attributedString: textView.attributedText)
//        let range = textView.selectedRange
//        mutaStr.replaceCharacters(in: textView.selectedRange, with: imageText)
//        textView.attributedText = mutaStr
//        textView.selectedRange = NSRange(location: range.location + 1, length: 0)
//        textView.delegate?.textViewDidChange?(textView)
    }
    
    //通知的监听方法
    @objc private func keyboardWillChange(n: Notification) {
        print(view.frame)
        let dict = n.userInfo!
        //UIKeyboardFrameEndUserInfoKey
        let endFrame = dict[UIKeyboardFrameEndUserInfoKey] as! CGRect
        //更新toolbar 底部约束
        let offsetY = -(ScreenHeight - endFrame.origin.y)
        UIView.animate(withDuration: 0.25) {
            self.toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offsetY)
            })
            
            //强制刷新
            self.view.layoutIfNeeded()
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}

//设置界面
extension WLMComposeViewController {
    
    func setSelectorController() {
        self.addChildViewController(pictureSelector)
        self.view.addSubview(pictureSelector.view)
        self.pictureSelector.view.isHidden = true
        pictureSelector.view.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(ScreenHeight/3*2)
        }
        self.view.bringSubview(toFront: toolBar)
    }
    
    func setNaviBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(titleName: "Close", target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = sendItem
        
        let lbl_title = UILabel()
        lbl_title.textAlignment = .center
        if let name = WLMUserAccountViewModel.shared.account?.screen_name {
            let text = "发布微博\n\(name)"
            lbl_title.text = text
            lbl_title.numberOfLines = 0
            
            let mStr = NSMutableAttributedString(string: text)
            
            let range = (text as NSString).range(of: name)
            mStr.addAttributes([NSForegroundColorAttributeName : UIColor.orange, NSFontAttributeName : UIFont.systemFont(ofSize: 14)], range: range)
            lbl_title.attributedText = mStr
        }
        else {
            lbl_title.text = "发布微博"
        }
        lbl_title.sizeToFit()
        navigationItem.titleView = lbl_title
    }
    
    func setTextView() {
        self.view.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(view)
            make.height.equalTo(ScreenHeight / 3)
        }
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
    }
    
    func setToolBar() {
        self.view.addSubview(toolBar)
        toolBar.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(40)
        }
    }
}

//协议实现
extension WLMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        sendItem.isEnabled = textView.hasText
        placeHolderLabel.isHidden = textView.hasText
    }
}
